package com.cloud.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.admin.common.constant.UserConstants;
import com.cloud.admin.common.exception.BusinessException;
import com.cloud.admin.common.utils.StringUtils;
import com.cloud.admin.mapper.*;
import com.cloud.admin.model.entity.*;
import com.cloud.admin.service.SysUserService;
import com.cloud.common.shiro.model.User;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息表
 *
 * @author douhaichao code generator
 * @date 2019-07-09 10:27:11
 */
@Service
@AllArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    private final SysUserMapper userMapper;

    private SysRoleMapper roleMapper;
    private SysPostMapper postMapper;
    private SysUserRoleMapper userRoleMapper;
    private SysUserPostMapper userPostMapper;

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    @Override
    public SysUser selectOne(SysUser req) {
        QueryWrapper queryWrapper = new QueryWrapper<SysUser>();
        queryWrapper.setEntity(req);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public String checkLoginNameUnique(String loginName) {
        int count = baseMapper.selectCount(new QueryWrapper<SysUser>().eq("login_name", loginName));
        if (count > 0) {
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }

    @Override
    public String checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1 : user.getUserId();
        SysUser info = baseMapper.selectOne(new QueryWrapper<SysUser>().eq("phonenumber", user.getPhonenumber()));
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.USER_PHONE_NOT_UNIQUE;
        }
        return UserConstants.USER_PHONE_UNIQUE;
    }

    @Override
    public String checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = baseMapper.selectOne(new QueryWrapper<SysUser>().eq("email", user.getEmail()));
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.USER_EMAIL_NOT_UNIQUE;
        }
        return UserConstants.USER_EMAIL_UNIQUE;
    }

    @Override
    public int changeStatus(SysUser user) {
        if (SysUser.isAdmin(user.getUserId())) {
            throw new BusinessException("不允许修改超级管理员用户");
        }
        return baseMapper.updateById(user);
    }

    @Override
    public String selectUserRoleGroup(Long userId) {
        List<SysRole> list = roleMapper.selectRolesByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public String selectUserPostGroup(Long userId) {
        List<SysPost> list = postMapper.selectPostsByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list) {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public User selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public IPage<SysUser> selectAllocatedList(Page page, SysUser user) {
        return userMapper.selectAllocatedList(page, user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public IPage<SysUser> selectUnallocatedList(Page page, SysUser user) {
        return userMapper.selectUnallocatedList(page, user);
    }

    /**
     * 根据条件查询所有
     */
    @Override
    public List<SysUser> selectAll(SysUser req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据对象查询所有分页数据(精确查询)     *      * @return
     */
    @Override
    public IPage<SysUser> selectPage(Page page, SysUser req) {
        IPage<SysUser> list = baseMapper.selectPage(
                page,
                new QueryWrapper<SysUser>().setEntity(req));
        return list;
    }

    /**
     * 根据对象查询所有分页数据(模糊查询)     *      * @return
     */
    @Override
    public IPage<SysUser> selectPageByLike(Page page, SysUser req) {
        QueryWrapper queryWrapper = new QueryWrapper();

        if (null != req.getUserId()) {
            queryWrapper.eq("user_id", req.getUserId());
        }

        if (null != req.getDeptId()) {
            queryWrapper.eq("dept_id", req.getDeptId());
        }

        if (!StrUtil.isEmpty(req.getLoginName())) {
            queryWrapper.like("login_name", req.getLoginName());
        }

        if (!StrUtil.isEmpty(req.getUserName())) {
            queryWrapper.like("user_name", req.getUserName());
        }

        if (!StrUtil.isEmpty(req.getUserType())) {
            queryWrapper.like("user_type", req.getUserType());
        }

        if (!StrUtil.isEmpty(req.getEmail())) {
            queryWrapper.like("email", req.getEmail());
        }

        if (!StrUtil.isEmpty(req.getPhonenumber())) {
            queryWrapper.like("phonenumber", req.getPhonenumber());
        }

        if (!StrUtil.isEmpty(req.getSex())) {
            queryWrapper.like("sex", req.getSex());
        }

        if (!StrUtil.isEmpty(req.getAvatar())) {
            queryWrapper.like("avatar", req.getAvatar());
        }

        if (!StrUtil.isEmpty(req.getPassword())) {
            queryWrapper.like("password", req.getPassword());
        }

        if (!StrUtil.isEmpty(req.getSalt())) {
            queryWrapper.like("salt", req.getSalt());
        }

        if (!StrUtil.isEmpty(req.getStatus())) {
            queryWrapper.like("status", req.getStatus());
        }

        if (!StrUtil.isEmpty(req.getDelFlag())) {
            queryWrapper.like("del_flag", req.getDelFlag());
        }

        if (!StrUtil.isEmpty(req.getLoginIp())) {
            queryWrapper.like("login_ip", req.getLoginIp());
        }

        if (null != req.getLoginDate()) {
            queryWrapper.eq("login_date", req.getLoginDate());
        }

        if (!StrUtil.isEmpty(req.getCreateBy())) {
            queryWrapper.like("create_by", req.getCreateBy());
        }

        if (null != req.getCreateTime()) {
            queryWrapper.eq("create_time", req.getCreateTime());
        }

        if (!StrUtil.isEmpty(req.getUpdateBy())) {
            queryWrapper.like("update_by", req.getUpdateBy());
        }

        if (null != req.getUpdateTime()) {
            queryWrapper.eq("update_time", req.getUpdateTime());
        }

        if (!StrUtil.isEmpty(req.getRemark())) {
            queryWrapper.like("remark", req.getRemark());
        }
        IPage<SysUser> list = baseMapper.selectPage(page, queryWrapper);
        return list;
    }

    @Override
    public IPage<SysUser> selectPageInfo(Page page, SysUser req) {
        return baseMapper.selectPageInfo(page, req);
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    @Override
    public int count(SysUser req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectCount(queryWrapper);
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = baseMapper.insert(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.delete(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.delete(new QueryWrapper<SysUserPost>().eq("user_id", userId));
        // 新增用户与岗位管理
        insertUserPost(user);
        return baseMapper.updateById(user);
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Integer[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Integer postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                userPostMapper.insertBatchUserPost(list);
            }
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        Integer[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Integer roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.insertBatchUserRole(list);
            }
        }
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public User selectUserByLoginName(String userName) {
        return userMapper.selectUserByLoginName(userName);
    }

    /**
     * 通过手机号码查询用户
     *
     * @param phoneNumber 手机号码
     * @return 用户对象信息
     */
    @Override
    public User selectUserByPhoneNumber(String phoneNumber) {
        return userMapper.selectUserByPhoneNumber(phoneNumber);
    }

    /**
     * 通过邮箱查询用户
     *
     * @param email 邮箱
     * @return 用户对象信息
     */
    @Override
    public User selectUserByEmail(String email) {
        return userMapper.selectUserByEmail(email);
    }

    /**
     * 修改用户个人详细信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserInfo(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public int resetUserPwd(User user) {
        return userMapper.updateUser(user);
    }
}
